package com.situ.company.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.company.entity.Department;
import com.situ.company.entity.Department;
import com.situ.company.util.JDBCUtil;
import com.situ.company.util.JSONResult;
import com.situ.company.util.JSONUtil;
import com.situ.company.vo.DepartmentCount;

@WebServlet("/department")
public class DepartmentServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");
		
		// 如果没有传递method参数，默认执行查找所有
		if (method == null || "".equals(method)) {
			//method = "findAll";
			method = "selectAll";
		}
		
		switch (method) {
		case "selectAll":
			selectAll(req, resp);
			break;
		case "del":
			del(req, resp);
			break;
		case "add":
			add(req, resp);
			break;
		case "getUpdatePage":
			getUpdatePage(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		case "selectDepartmentCount":
			selectDepartmentCount(req, resp);
			break;
		default:
			break;
		}
	}
	
	private void selectDepartmentCount(HttpServletRequest req, HttpServletResponse resp) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		ArrayList<DepartmentCount> list = new ArrayList<DepartmentCount>();
		// 加载驱动
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "SELECT d.name,COUNT(*) as count FROM employee as e INNER JOIN department as d ON e.code_dept = d.`code`  GROUP BY d.`code` ;";
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			System.out.println(preparedStatement);
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				String name = resultSet.getString("name");
				int count = resultSet.getInt("count");
				DepartmentCount departmentCount = new DepartmentCount(name, count);
				list.add(departmentCount);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		for (DepartmentCount departmentCount : list) {
			System.out.println(departmentCount);
		}
		
		JSONResult jsonResult = JSONResult.success(list);
		JSONUtil.obj2Json(jsonResult, resp);
	}

	private void update(HttpServletRequest req, HttpServletResponse resp) {
		String id = req.getParameter("id");
		String code = req.getParameter("code");
		String name = req.getParameter("name");
		String tel = req.getParameter("tel");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		int count = 0;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "update department set code=?,name=?,tel=? where id=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, code);
			preparedStatement.setString(2, name);
			preparedStatement.setString(3, tel);
			preparedStatement.setInt(4, Integer.parseInt(id));
			count = preparedStatement.executeUpdate();
			System.out.println(preparedStatement);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		if (count == 1) {
			JSONResult jsonResult = JSONResult.success("修改成功");
			JSONUtil.obj2Json(jsonResult, resp);
		} else {
			JSONResult jsonResult = JSONResult.error("修改失败");
			JSONUtil.obj2Json(jsonResult, resp);
		}
	}

	// 通过转发的方式跳转到update.jsp页面
	private void getUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String updateId = req.getParameter("id");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		Department department = null;
		// 加载驱动
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "select id,code,name,tel from department where id=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, Integer.parseInt(updateId));
			resultSet = preparedStatement.executeQuery();
			System.out.println(preparedStatement);
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String code = resultSet.getString("code");
				String name = resultSet.getString("name");
				String tel = resultSet.getString("tel");
				department = new Department(id, code, name, tel);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		req.setAttribute("department", department);
		req.getRequestDispatcher("/web/page/department/update.jsp").forward(req, resp);
	}

	private void add(HttpServletRequest req, HttpServletResponse resp) {
		String code = req.getParameter("code");
		String name = req.getParameter("name");
		String tel = req.getParameter("tel");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		int count = 0;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "INSERT INTO department(code,`name`,tel) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, code);
			preparedStatement.setString(2, name);
			preparedStatement.setString(3, tel);
			count = preparedStatement.executeUpdate();
			System.out.println(preparedStatement);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		if (count == 1) {
			JSONResult jsonResult = JSONResult.success("添加成功");
			JSONUtil.obj2Json(jsonResult, resp);
		} else {
			JSONResult jsonResult = JSONResult.error("添加失败");
			JSONUtil.obj2Json(jsonResult, resp);
		}
	}

	private void del(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("DepartmentServlet.del()");
		String code = req.getParameter("code");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		int count = 0;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "delete from department where code=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, code);
			count = preparedStatement.executeUpdate();
			System.out.println(preparedStatement);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		if (count == 1) {
			JSONResult jsonResult = JSONResult.success("删除成功");
			JSONUtil.obj2Json(jsonResult, resp);
		} else {
			JSONResult jsonResult = JSONResult.error("删除失败");
			JSONUtil.obj2Json(jsonResult, resp);
		}
	}

	private void selectAll(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("DepartmentServlet.selectAll()");
		// 得到搜索的名字
		String searchName = req.getParameter("name");
		if (searchName == null) {
			searchName = "";
		}
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		ArrayList<Department> list = new ArrayList<Department>();
		// 加载驱动
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "select id,code,name,tel from department where name like ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, '%' + searchName + '%');
			resultSet = preparedStatement.executeQuery();
			System.out.println(preparedStatement);
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String code = resultSet.getString("code");
				String name = resultSet.getString("name");
				String tel = resultSet.getString("tel");
				Department department = new Department(id, code, name, tel);
				list.add(department);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		for (Department department : list) {
			System.out.println(department);
		}
		
		JSONResult jsonResult = JSONResult.success(list);
		JSONUtil.obj2Json(jsonResult, resp);
	}
}
